package com.lishu.carsafe.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.lishu.carsafe.R;
import com.lishu.carsafe.adapter.FaultListAdapter;
import com.lishu.carsafe.adapter.TaskListAdapter;
import com.lishu.carsafe.http.HttpBase;
import com.lishu.carsafe.http.HttpLoader;
import com.lishu.carsafe.listener.DateSearchListener;
import com.lishu.carsafe.model.BaseModel;
import com.lishu.carsafe.model.FaultListModel;
import com.lishu.carsafe.model.TaskModel;
import com.lishu.carsafe.utils.ClickUtil;
import com.lishu.carsafe.utils.DateSearchUtil;
import com.lishu.carsafe.utils.ListUtil;
import com.lishu.carsafe.utils.StringUtil;
import com.lishu.carsafe.utils.ToastUtil;
import com.lishu.carsafe.widget.DialogUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import static com.scwang.smartrefresh.layout.util.SmartUtil.dp2px;

public class FaultActivity extends BaseSearchActivity implements View.OnClickListener{
    private EditText begin_time_ev, end_time_ev;
    private String chooseBeginTime, chooseEndTime;
    private SwipeMenuListView fault_list;
    private FaultListAdapter mFaultListAdapter;
    private int curPage;
    private SmartRefreshLayout refreshLayout;
    private LinearLayout no_fault_layout;
    private List<FaultListModel.FaultBean> mFaultList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fault);
        
        chooseBeginTime = "";//TimeUtil.getCurDatetime();
        chooseEndTime = "";//TimeUtil.getCurDatetime();

        initView();
        initEvent();
        showFaultList();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getFaultListByTime(1, chooseBeginTime, chooseEndTime);
        //testData();
    }

    private void initView() {
        setTopTitle(R.string.module_fault);
        setTopRight(R.drawable.icon_add);
        begin_time_ev = findViewById(R.id.begin_time_ev);
        end_time_ev = findViewById(R.id.end_time_ev);
        fault_list = findViewById(R.id.fault_list);
        mFaultListAdapter = new FaultListAdapter(this);
        fault_list.setAdapter(mFaultListAdapter);

        refreshLayout = findViewById(R.id.refreshLayout);
        refreshLayout.setEnableRefresh(false);
        no_fault_layout = findViewById(R.id.no_fault_layout);

        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
                deleteItem.setBackground(R.color.red_button);
                deleteItem.setWidth(dp2px(80));
                deleteItem.setTitle("撤销");
                //deleteItem.setIcon(R.drawable.icon_repeal);
                deleteItem.setTitleSize(15);
                deleteItem.setTitleColor(Color.WHITE);
                menu.addMenuItem(deleteItem);
            }
        };
        fault_list.setMenuCreator(creator);
        fault_list.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                FaultListModel.FaultBean faultBean = mFaultList.get(position);
                final String id = faultBean.getId();
                DialogUtil.showDeleteDialog(mContext, new DialogUtil.OnDeleteButtonClickListener() {
                    @Override
                    public void onDeleteButtonClick() {
                        faultRepeal(id, position);
                    }
                });
                return false;// false : close the menu; true : not close the menu
            }
        });
    }

    private void testData() {
        //@@@@@@@@@@@@@@@@@@ just for testing, begin @@@@@@@@@@@@@@@@@
        List<FaultListModel.FaultBean> faultList = new ArrayList<>();
        faultList.add(new FaultListModel().new FaultBean("1","任务名称1", "我公司在今天下午进行员工总结大会", "20181209121514"));
        faultList.add(new FaultListModel().new FaultBean("2","任务名称2", "城管局如何做好巡检工作", "20181209101510"));
        faultList.add(new FaultListModel().new FaultBean("3","任务名称3", "冬季如何做好防护工作", "20181209111836"));
        faultList.add(new FaultListModel().new FaultBean("4","任务名称4", "我公司在今天下午进行员工总结大会，请全体人员都准时参加活动", "20181216091842"));
        mFaultList.addAll(faultList);
        mFaultListAdapter.setData(mFaultList);
        //@@@@@@@@@@@@@@@@@@ just for testing, end @@@@@@@@@@@@@@@@@@
    }

    private void initEvent() {
        findViewById(R.id.title_right).setOnClickListener(this);
        begin_time_ev.setOnClickListener(this);
        end_time_ev.setOnClickListener(this);
        findViewById(R.id.search_button).setOnClickListener(this);
        fault_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
                String faultId = ((FaultListModel.FaultBean)parent.getItemAtPosition(position)).getId();
                Intent intent = new Intent(FaultActivity.this, FaultDetailActivity.class);
                intent.putExtra("faultId", faultId);
                startActivity(intent);
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                curPage++;
                if (StringUtil.isEmpty(chooseBeginTime) && StringUtil.isEmpty(chooseEndTime)) {
                    getFaultList("", "", curPage, COUNT_PER_PAGE);
                }else {                    
                    getFaultList(chooseBeginTime, chooseEndTime, curPage, COUNT_PER_PAGE);
                }
                refreshLayout.finishLoadMore();
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.begin_time_ev:
                showDatePickerDialog(0);
                break;
            case R.id.end_time_ev:
                showDatePickerDialog(1);
                break;
            case R.id.search_button:
                if (ClickUtil.isFastClick()) {
                    return ;
                }
                search();
                break;
            case R.id.title_right:
                Intent intent = new Intent(FaultActivity.this, FaultAddActivity.class);
                startActivity(intent);
                break;

        }
    }

    private void search() {
        final String beginDate = begin_time_ev.getText().toString();
        final String endDate = end_time_ev.getText().toString();
        DateSearchUtil.searchByDate(beginDate, endDate, new DateSearchListener() {
            @Override
            public void searchByDefaultDate() {
                getFaultListByTime(1, "", "");
            }

            @Override
            public void searchByChooseDate(String beginDate, String endDate) {
                getFaultListByTime(1, beginDate, endDate);
            }
        });
    }

    private void getFaultListByTime(int page, String beginDate, String endDate){
        if(page == 1){
            curPage = 1;
            mFaultList.clear();
        }
        chooseBeginTime = beginDate;
        chooseEndTime = endDate;

        if (StringUtil.isEmpty(beginDate) && StringUtil.isEmpty(endDate)){
            getFaultList("", "", curPage, COUNT_PER_PAGE);
        }else {
            getFaultList(beginDate, endDate, curPage, COUNT_PER_PAGE);
        }
    }

    private void getFaultList(String beginTime, String endTime, int curPage, final int count){
        String bTime = beginTime.replace("/", "-");
        String eTime = endTime.replace("/", "-");
        HttpLoader.getFaultList(bTime, eTime, curPage, count, new HttpBase.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    mFaultList.clear();
                    mFaultListAdapter.setData(mFaultList);
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }

                List<FaultListModel.FaultBean> faultList = ((FaultListModel) model).getData();
                if (faultList != null) {
                    mFaultList.addAll(faultList);
                }else{
                    ToastUtil.showShort(R.string.no_more_data);
                }
                showFaultList();
                //mFaultListAdapter.setData(mFaultList);
            }
        });
    }

    private void showFaultList() {
        if(ListUtil.isEmpty(mFaultList)){
            no_fault_layout.setVisibility(View.VISIBLE);
            refreshLayout.setVisibility(View.GONE);
        }else{
            no_fault_layout.setVisibility(View.GONE);
            refreshLayout.setVisibility(View.VISIBLE);
            mFaultListAdapter.setData(mFaultList);
        }
    }

    private void faultRepeal(String id, final int position) {
        HttpLoader.faultRepeal(id, new HttpLoader.IResponseListener() {
            @Override
            public void onResponse(BaseModel model) {
                if (model == null) {
                    ToastUtil.showShort(R.string.please_check_network);
                    return;
                }
                if (!model.success()) {
                    ToastUtil.showShort(getString(R.string.get_data_fail) + model.getMsg());
                    return;
                }

                ToastUtil.showShort("撤销成功");
                mFaultList.remove(position);
                showFaultList();
                //mFaultListAdapter.setData(mFaultList);
            }
        });
    }

}
